package com.ruoyi.slope.gateway.util;

import com.ruoyi.slope.gateway.domain.SlopeGatewayInfo;
import com.ruoyi.slope.gateway.mapper.SlopeGatewayInfoMapper;
import com.ruoyi.slope.gateway.service.impl.SlopeGatewayInfoServiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class IOClient {

    static String ip = "127.0.0.1";
    static int port = 9001;

    public static int alarm(String gatewaySn) throws IOException {
        OutputStream writer = null;
        InputStream reader = null;
        Socket socket = null;
        try {
            SocketAddress socketAddress = new InetSocketAddress(ip, port);
            socket = new Socket();
            socket.connect(socketAddress, 6000);
            System.out.println("连接服务器: " + socket.getRemoteSocketAddress());

            if (!socket.isConnected() || !socket.isBound()) {
                throw new IOException("无法连接到服务器！");
            } else {
                System.out.println("已成功连接到服务器！");
            }

            // 构造报文：CCDD + gatewaySn + 固定部分
            String hexString = "CCDD" + gatewaySn.toUpperCase() + "03020001010000";

            byte[] bytes = hexStringToByteArray(hexString);
            writer = socket.getOutputStream();
            writer.write(bytes);
            writer.flush();

            System.out.println("已发送十六进制串: " + hexString);
            System.out.println("等待服务器响应...");

            // 接收服务器响应
            reader = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = reader.read(buffer);

            if (bytesRead != -1) {
                String response = bytesToHexString(buffer, bytesRead);
                System.out.println("接收到服务器响应: " + response);
                return 1; // 成功
            } else {
                System.out.println("未收到服务器响应");
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                if (reader != null) reader.close();
                if (writer != null) writer.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static int cancelAlarm(String gatewaySn) throws IOException {
        OutputStream writer = null;
        InputStream reader = null;
        Socket socket = null;
        try {
            SocketAddress socketAddress = new InetSocketAddress(ip, port);
            socket = new Socket();
            socket.connect(socketAddress, 6000);
            System.out.println("连接服务器: " + socket.getRemoteSocketAddress());

            if (!socket.isConnected() || !socket.isBound()) {
                throw new IOException("无法连接到服务器！");
            } else {
                System.out.println("已成功连接到服务器！");
            }

            // 构造报文：CCDD + gatewaySn + 固定部分
            String hexString = "CCDD" + gatewaySn.toUpperCase() + "03020001000000";

            byte[] bytes = hexStringToByteArray(hexString);
            writer = socket.getOutputStream();
            writer.write(bytes);
            writer.flush();

            System.out.println("已发送十六进制串: " + hexString);
            System.out.println("等待服务器响应...");

            // 接收服务器响应
            reader = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = reader.read(buffer);

            if (bytesRead != -1) {
                String response = bytesToHexString(buffer, bytesRead);
                System.out.println("接收到服务器响应: " + response);
                return 1; // 成功
            } else {
                System.out.println("未收到服务器响应");
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                if (reader != null) reader.close();
                if (writer != null) writer.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static int getData(String gatewaySn) throws IOException {
        OutputStream writer = null;
        InputStream reader = null;
        Socket socket = null;
        try {
            SocketAddress socketAddress = new InetSocketAddress(ip, port);
            socket = new Socket();
            socket.connect(socketAddress, 6000);
            System.out.println("连接服务器: " + socket.getRemoteSocketAddress());

            if (!socket.isConnected() || !socket.isBound()) {
                throw new IOException("无法连接到服务器！");
            } else {
                System.out.println("已成功连接到服务器！");
            }

            // 构造报文：CCDD + gatewaySn + 固定部分
            String hexString = "CCDD" + gatewaySn.toUpperCase() + "030500000000";

            byte[] bytes = hexStringToByteArray(hexString);
            writer = socket.getOutputStream();
            writer.write(bytes);
            writer.flush();

            System.out.println("已发送十六进制串: " + hexString);
            System.out.println("等待服务器响应...");

            // 接收服务器响应
            reader = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = reader.read(buffer);

            if (bytesRead != -1) {
                String response = bytesToHexString(buffer, bytesRead);
                System.out.println("接收到服务器响应: " + response);
                return 1; // 成功
            } else {
                System.out.println("未收到服务器响应");
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                if (reader != null) reader.close();
                if (writer != null) writer.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static int getDataTime(String gatewaySn, String time) throws IOException {
        OutputStream writer = null;
        InputStream reader = null;
        Socket socket = null;
        try {
            SocketAddress socketAddress = new InetSocketAddress(ip, port);
            socket = new Socket();
            socket.connect(socketAddress, 6000);
            System.out.println("连接服务器: " + socket.getRemoteSocketAddress());

            if (!socket.isConnected() || !socket.isBound()) {
                throw new IOException("无法连接到服务器！");
            } else {
                System.out.println("已成功连接到服务器！");
            }

            // 构造报文：CCDD + gatewaySn + 固定部分
            String hexString = "CCDD" + gatewaySn.toUpperCase() + "03030002"+time+"0000";

            byte[] bytes = hexStringToByteArray(hexString);
            writer = socket.getOutputStream();
            writer.write(bytes);
            writer.flush();

            System.out.println("已发送十六进制串: " + hexString);
            System.out.println("等待服务器响应...");

            // 接收服务器响应
            reader = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = reader.read(buffer);

            if (bytesRead != -1) {
                String response = bytesToHexString(buffer, bytesRead);
                System.out.println("接收到服务器响应: " + response);
                return 1; // 成功
            } else {
                System.out.println("未收到服务器响应");
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                if (reader != null) reader.close();
                if (writer != null) writer.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 16进制字符串转字节数组
     */
    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * 字节数组转16进制字符串
     */
    public static String bytesToHexString(byte[] bytes, int length) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {
            result.append(String.format("%02X", bytes[i]));
        }
        return result.toString();
    }
}
